package com.webdrider.servlet.action.blog;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.common.security.exceptions.ManagerException;
import com.common.security.exceptions.ParserException;
import com.common.servlet.abstracts.AbstractJSONParser;
import com.common.servlet.abstracts.AbstractSimpleServlet;
import com.webdrider.manager.action.blog.PostManager;
import com.webdrider.manager.interfaces.IPostManager;
import com.webdrider.model.action.blog.Post;
import com.webdrider.model.response.blog.GetBlogPostResponse;
import com.webdrider.security.exceptions.BlogException;
import com.webdrider.servlet.util.RequestAction;
import com.webdrider.servlet.util.parser.blog.GetBlogPostJSONParser;

public class GetBlogPostServlet extends AbstractSimpleServlet {
	private static final long serialVersionUID = 1L;
	
	private IPostManager postManager = new PostManager();
	private GetBlogPostJSONParser parser = new GetBlogPostJSONParser();
	
	public void handle(HttpServletRequest request, HttpServletResponse response) throws ManagerException, IOException {
		try {
			GetBlogPostResponse blogPostResponse = new GetBlogPostResponse();
			
			String postName = request.getParameter("post");
			Post post;
			
			if (postName != null) {
				post = postManager.getPost(postName);
			} else {
				post = postManager.getLatestPost();
			}
			
			blogPostResponse.setRequestAction(RequestAction.GET_BLOG_POST);
			blogPostResponse.setPost(post);
			
			response.setContentType("json");
			response.getWriter().write(parser.parseResponse(blogPostResponse));
			response.getWriter().close();
		} catch (BlogException blogException) {
			//ignore it for now
		} catch (ParserException parserException) {
			exception(parserException, response);
		}
	}

	@Override
	public AbstractJSONParser parser() {
		return parser;
	}
}
